const { Service } = require("egg");
const { Op } = require("sequelize");

class EnterpriseCertificateService extends Service {
  async create(data) {
    const enterpriseCertificate =
      await this.ctx.model.EnterpriseCertificate.create(data);
    return enterpriseCertificate;
  }

  async createOrUpdate(data) {
    try {
      let existingRecord = await this.ctx.model.EnterpriseCertificate.findOne({
        where: { certificateNumber: data.certificateNumber },
      });

      if (existingRecord) {
        await existingRecord.update(data);
        console.log("Record updated");
      } else {
        await this.ctx.model.EnterpriseCertificate.create({ ...data });
        console.log("Record created");
      }
    } catch (error) {
      console.error("Error handling certificate:", error);
    }
  }

  async findAll(filter = {}) {
    try {
      const { pageNum = 1, pageSize = 20, search } = filter;
      const offset = (pageNum - 1) * pageSize;
      let whereConditions = { isDeleted: 0 };

      if (search) {
        whereConditions = {
          ...whereConditions,
          [Op.or]: [
            { enterpriseName: { [Op.like]: `%${search}%` } },
            { certificateNumber: { [Op.like]: `%${search}%` } },
          ],
        };
      }

      const datas = await this.ctx.model.EnterpriseCertificate.findAll({
        where: whereConditions,
        limit: pageSize,
        offset,
        order: [["createdAt", "DESC"]],
        attributes: { exclude: ["updatedAt", "createdAt"] },
      });

      const total = await this.ctx.model.EnterpriseCertificate.count({
        where: whereConditions,
      });

      const hasNextPage = offset + pageSize < total;
      return {
        total,
        pageNum,
        pageSize,
        hasNextPage,
        sorts: datas,
      };
    } catch (error) {
      throw new Error(error);
    }
  }

  async findById(id) {
    try {
      const enterpriseCertificate =
        await this.ctx.model.EnterpriseCertificate.findByPk(id, {
          attributes: { exclude: ["updatedAt", "createdAt"] },
        });
      if (!enterpriseCertificate) {
        throw new Error("未找到对应的企业证书");
      }
      return enterpriseCertificate;
    } catch (error) {
      throw new Error("查找企业证书时发生错误");
    }
  }

  async update(id, updates) {
    const updated = await this.ctx.model.EnterpriseCertificate.update(updates, {
      where: { id },
    });
    if (updated[0] === 0) {
      throw new Error("未找到可更新的企业证书");
    }
    return { success: true };
  }

  getYear(date) {
    console.log(date, "date");
    return this.ctx.helper.formatDate(date, "yyyy");
  }

  async updateAnnualInspectionYears(id, date) {
    const enterpriseCertificate =
      await this.ctx.model.EnterpriseCertificate.findByPk(id);

    if (!enterpriseCertificate) {
      throw new Error("未找到对应的企业证书");
    }

    const { validityStartDate, validityEndDate } = enterpriseCertificate;

    const max =
      this.getYear(validityEndDate) - this.getYear(validityStartDate) - 1;

    if (max <= 0) {
      throw new Error("该证书有效期只有一年，无需年检");
    }

    let { annualInspectionYears = [] } = enterpriseCertificate;

    const currentYear = this.getYear(date);

    const yearExists = annualInspectionYears.some((timestamp) => {
      return this.getYear(new Date(timestamp)) === currentYear;
    });

    if (yearExists) {
      throw new Error(`${currentYear} 已年检，无需重复年检`);
    }

    annualInspectionYears = [...annualInspectionYears, date];

    console.log("annualInspectionYears", annualInspectionYears);

    annualInspectionYears = annualInspectionYears
      .slice(-max)
      .sort((a, b) => b - a);

    const updated = await this.ctx.model.EnterpriseCertificate.update(
      { annualInspectionYears },
      {
        where: { id },
      }
    );
    if (updated[0] === 0) {
      throw new Error("未找到可更新的企业证书");
    }
    return updated;
  }

  async delete(id) {
    const deleted = await this.ctx.model.EnterpriseCertificate.update(
      { isDeleted: 1 },
      { where: { id } }
    );
    if (deleted[0] === 0) {
      throw new Error("未找到可删除的企业证书");
    }
    return { success: true };
  }
}

module.exports = EnterpriseCertificateService;
